package com.squeekeek.util.qrcode.Ui;

import java.io.File;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import com.squeekeek.util.qrcode.R;

import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.Toast;

public class ViewScreen extends FragmentActivity implements InfoFragment.OnButtonClick {
	private Camera cameraHandle;
	private CameraSurfaceHolder cameraViewHolder;
	private Button captureBtn = null;
	
	private BaseLoaderCallback OpenCVCallbackh = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch(status) {
				case LoaderCallbackInterface.SUCCESS:
					break;
				case LoaderCallbackInterface.INIT_FAILED:
					finish();
					break;
				default:
					super.onManagerConnected(status);
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Check whether the OpenCV manager is already opened
		if(OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, OpenCVCallbackh)) {
			setContentView(R.layout.activity_view);
			
			// Set window format
			getWindow().setFormat(PixelFormat.TRANSLUCENT);
			
			// Get capture button instance
			this.captureBtn = (Button) findViewById(R.id.btn_capture2);
		}
	}
	
	@Override
	public void onResume() {
		SurfaceView cameraView = null;
		CaptureButtonClickListener cbclListener = null;
		
		super.onResume();
		
		try {
			// Get camera
			this.cameraHandle = this.getCameraInstance();
			
			// Set camera preview
			cameraView = (SurfaceView) findViewById(R.id.view_camera);

			if(this.cameraViewHolder == null) {
				this.cameraViewHolder = new CameraSurfaceHolder(this.cameraHandle, cameraView.getHolder());
			}
			
			// Set button listener
			cbclListener = new CaptureButtonClickListener(this.cameraHandle, this);
			captureBtn.setOnClickListener(cbclListener);
		}
		catch(Exception e) {
			// The preview has been started or the camera
			// cannot be accessed. Try to release camera if
			// it has been set
			this.releaseCameraInstance(this.cameraHandle);
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		
		// NOTE: Camera is released when preview is destroyed.
		// Release camera, null holders and button listeners
		this.releaseCameraInstance(this.cameraHandle);
		this.cameraViewHolder = null;
		this.captureBtn.setOnClickListener(null);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.action_clean:
			try {
				this.clearAppDir();
				Toast.makeText(this, "App directory cleared!", Toast.LENGTH_LONG).show();
				return true;
			}
			catch(Exception e) {
				Toast.makeText(this, "App directory not yet cleared.", Toast.LENGTH_LONG).show();
				return false;
			}
		case R.id.action_settings:
			Toast.makeText(this, "No settings yet... :D", Toast.LENGTH_LONG).show();
			return true;
		case R.id.action_about:
			openAboutScreen();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCancelButtonClick() {
		FragmentTransaction winManager;
		InfoFragment myFragment;
		
		// Close the fragment
		winManager = getSupportFragmentManager().beginTransaction();
		myFragment = (InfoFragment) getSupportFragmentManager().findFragmentById(R.id.ui_view);
		winManager.remove(myFragment);
		winManager.commit();
	}
	
	private void openAboutScreen() {
		startActivity(new Intent(this, AboutScreen.class));
	}
	
	private Camera getCameraInstance() {
		Camera c = null;
		
		try {
			c = Camera.open();
		}
		catch(Exception e) {
		}
		
		return c;
	}
	
	private void releaseCameraInstance(Camera c) {
		if(c != null) {
			c.release();
			c = null;
		}
	}
	
	private void clearAppDir() throws Exception {
		File appMediaDir;
		File[] fileList;
		
		appMediaDir = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "qrcode");
		
		if(appMediaDir.isDirectory()) {
			fileList = appMediaDir.listFiles();
			
			for(File iFile : fileList) {
				iFile.delete();
			}
		}
	}
}
